<template>
  <a-drawer
    title="设计表单"
    :maskClosable="false"
    :mask="true"
    width=100%
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="formVisiable">
    <fm-making-form ref="makingform" style="height: 900px;" upload preview clearable generateJson :customFields="formMakingCustomPlugins">
      <template slot="action">
        <el-col :span="6"><el-input v-model="FormData.formName" type="text" size="mini" placeholder="表单名称"/> </el-col>
        <el-button type="text" icon="el-icon-upload" @click="save">保存</el-button>
        <el-button type="text" icon="el-icon-close" @click="onClose">关闭</el-button>
      </template>
    </fm-making-form>
  </a-drawer>
</template>
<script>
import customPlugins from './FormMakingCustomPlugins'

export default {
  name: 'AddForm',
  props: {
    formVisiable: {
      default: false
    }
  },
  data () {
    return {
      formMakingCustomPlugins: customPlugins.customFields,
      FormData: {},
      onceFlag: true
    }
  },
  methods: {
    save () {
      if (!this.FormData.formName) {
        this.$message.error('表单名称不可为空')
      } else {
        this.FormData.formJson = JSON.stringify(this.$refs.makingform.getJSON())
        this.$post('form', {
          ...this.FormData
        }).then((r) => {
          this.$emit('success')
        }).catch(() => {
          this.loading = false
        })
      }
    },
    setFormData (formdata) {
      this.FormData = formdata
    },
    onClose () {
      this.$emit('close')
    }
  },
  updated: function () {
    if (this.formVisiable && this.$refs.makingform && this.onceFlag && this.FormData.formJson) {
      this.$refs.makingform.setJSON(this.FormData.formJson)
      this.onceFlag = false
    }
  },
  watch: {
    formVisiable () {
      if (this.formVisiable && !this.onceFlag) {
        this.onceFlag = !this.onceFlag
      }
    }
  }
}
</script>
